/**
 * futures : masterlink.futures.dao.GroupDao.java
 */
package masterlink.futures.dao;

import java.util.ArrayList;
import java.util.List;

import masterlink.futures.vo.Account;
import masterlink.futures.vo.Alert;
import masterlink.futures.vo.AlertBalance;
import masterlink.futures.vo.AlertGreeks;
import masterlink.futures.vo.Group;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import baytony.util.Util;

/**
 * TODO Write the description
 *
 * @author : tonyyang
 * Create date : 2011/10/25
 * @version 1.0.0	
 */
@Repository
@Qualifier("AlertDao")
public class AlertDao extends TimesTenTemplateDao{
	
	private static final String FIND_GROUP_ALERT="select a.* " +
												 "from greeks_alert_balance a " +
												 "where a.id in (select max(b.id) from greeks_alert_balance b "+
												 	"where b.broker=':broker') " +
												 "order by a.id desc";
	private static final String FIND_ACC_ALERT="select b.*,c.* " +
												"from greeks_limit a,fuminv b, greeks_alert_greek c " +
												"where a.broker=b.broker_id and a.account=b.acno " +
												"and a.broker=c.broker and a.account=c.account " +
												"and a.id=? " +
												"and c.id in (select f.id from (select max(e.id) as id, e.broker, e.account "+
												"from greeks_alert_greek e where e.broker=':broker'"+
												"group by e.broker, e.account "+
												") f) " +
												"order by c.id desc";
	
	public List<Alert> findGroupAlert(Group g){
		if(g!=null && Util.parseBoolean(g.getSystem())){
			List<AlertBalance> all=findBySql(FIND_GROUP_ALERT.replaceAll(":broker", g.getName()), AlertBalance.class );
			if(!Util.isEmptyList(all)){
				List<Alert> res=new ArrayList<Alert>();
				for(AlertBalance o:all){
					res.add(new Alert(g, o));
				}
				return res;
			}
		}
		log.trace("{} is not a valid group to find alert",(g==null?"null":g.toString()));
		return null;
	}
	
	public List<Alert> findAccAlert(Group g){
		if(g!=null && Util.parseBoolean(g.getSystem())){
			List<Object[]> all= findBySql(FIND_ACC_ALERT.replaceAll(":broker", g.getName()),new Class<?>[]{Account.class,AlertGreeks.class}, g.getId());
			if(!Util.isEmptyList(all)){
				List<Alert> res=new ArrayList<Alert>();
				for(Object[] o:all){
					res.add(new Alert(g,(Account)o[0],(AlertGreeks)o[1]));
				}
				return res;
			}
		}
		log.trace("{} is not a valid group to find alert",(g==null?"null":g.toString()));
		return null;
	}
	
	
	public List<Alert> findAlerts(Group g){
		List<Alert> res=new ArrayList<Alert>();
		List<Alert> a=findGroupAlert(g);
		if(a!=null){
			res.addAll(a);
		}
		a=findAccAlert(g);
		if(a!=null){
			res.addAll(a);
		}
		return res;
	}
}
